<template>
  <el-dialog
    v-model="dialogVisible"
    title="全局设置"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 通知设置 -->
      <el-tab-pane label="通知设置" name="notification">
        <el-form :model="notificationSettings" label-width="120px">
          <el-form-item label="短信服务">
            <el-switch v-model="notificationSettings.smsEnabled" />
            <span class="setting-desc">启用短信通知功能</span>
          </el-form-item>
          
          <el-form-item label="短信服务商" v-if="notificationSettings.smsEnabled">
            <el-select v-model="notificationSettings.smsProvider" style="width: 200px">
              <el-option label="阿里云短信" value="aliyun" />
              <el-option label="腾讯云短信" value="tencent" />
              <el-option label="华为云短信" value="huawei" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="短信签名" v-if="notificationSettings.smsEnabled">
            <el-input v-model="notificationSettings.smsSignature" placeholder="请输入短信签名" style="width: 300px" />
          </el-form-item>
          
          <el-form-item label="邮件服务">
            <el-switch v-model="notificationSettings.emailEnabled" />
            <span class="setting-desc">启用邮件通知功能</span>
          </el-form-item>
          
          <el-form-item label="SMTP服务器" v-if="notificationSettings.emailEnabled">
            <el-input v-model="notificationSettings.smtpServer" placeholder="smtp.example.com" style="width: 300px" />
          </el-form-item>
          
          <el-form-item label="SMTP端口" v-if="notificationSettings.emailEnabled">
            <el-input-number v-model="notificationSettings.smtpPort" :min="1" :max="65535" />
          </el-form-item>
          
          <el-form-item label="发件人邮箱" v-if="notificationSettings.emailEnabled">
            <el-input v-model="notificationSettings.senderEmail" placeholder="sender@example.com" style="width: 300px" />
          </el-form-item>
          
          <el-form-item label="微信推送">
            <el-switch v-model="notificationSettings.wechatEnabled" />
            <span class="setting-desc">启用微信企业号推送</span>
          </el-form-item>
          
          <el-form-item label="企业ID" v-if="notificationSettings.wechatEnabled">
            <el-input v-model="notificationSettings.wechatCorpId" placeholder="请输入企业ID" style="width: 300px" />
          </el-form-item>
          
          <el-form-item label="应用Secret" v-if="notificationSettings.wechatEnabled">
            <el-input v-model="notificationSettings.wechatSecret" type="password" placeholder="请输入应用Secret" style="width: 300px" />
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 系统设置 -->
      <el-tab-pane label="系统设置" name="system">
        <el-form :model="systemSettings" label-width="120px">
          <el-form-item label="预警频率限制">
            <el-input-number v-model="systemSettings.warningFrequencyLimit" :min="1" :max="60" />
            <span class="setting-desc">分钟内相同规则最多触发次数</span>
          </el-form-item>
          
          <el-form-item label="数据保留期">
            <el-input-number v-model="systemSettings.dataRetentionDays" :min="30" :max="3650" />
            <span class="setting-desc">预警记录保留天数</span>
          </el-form-item>
          
          <el-form-item label="自动清理">
            <el-switch v-model="systemSettings.autoCleanup" />
            <span class="setting-desc">自动清理过期数据</span>
          </el-form-item>
          
          <el-form-item label="清理时间" v-if="systemSettings.autoCleanup">
            <el-time-picker
              v-model="systemSettings.cleanupTime"
              format="HH:mm"
              placeholder="选择清理时间"
            />
          </el-form-item>
          
          <el-form-item label="日志级别">
            <el-select v-model="systemSettings.logLevel" style="width: 200px">
              <el-option label="DEBUG" value="debug" />
              <el-option label="INFO" value="info" />
              <el-option label="WARN" value="warn" />
              <el-option label="ERROR" value="error" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="最大并发数">
            <el-input-number v-model="systemSettings.maxConcurrency" :min="1" :max="100" />
            <span class="setting-desc">同时处理的最大预警数量</span>
          </el-form-item>
          
          <el-form-item label="超时时间">
            <el-input-number v-model="systemSettings.timeoutSeconds" :min="5" :max="300" />
            <span class="setting-desc">预警处理超时时间（秒）</span>
          </el-form-item>
          
          <el-form-item label="重试次数">
            <el-input-number v-model="systemSettings.retryCount" :min="0" :max="10" />
            <span class="setting-desc">失败后重试次数</span>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 阈值设置 -->
      <el-tab-pane label="阈值设置" name="threshold">
        <el-form :model="thresholdSettings" label-width="120px">
          <h4>水位阈值</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="正常水位">
                <el-input-number v-model="thresholdSettings.waterLevel.normal" :precision="2" />
                <span class="unit">m</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="警戒水位">
                <el-input-number v-model="thresholdSettings.waterLevel.warning" :precision="2" />
                <span class="unit">m</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="危险水位">
                <el-input-number v-model="thresholdSettings.waterLevel.danger" :precision="2" />
                <span class="unit">m</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="极限水位">
                <el-input-number v-model="thresholdSettings.waterLevel.critical" :precision="2" />
                <span class="unit">m</span>
              </el-form-item>
            </el-col>
          </el-row>

          <h4>流量阈值</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="正常流量">
                <el-input-number v-model="thresholdSettings.flow.normal" :precision="2" />
                <span class="unit">m³/s</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="警戒流量">
                <el-input-number v-model="thresholdSettings.flow.warning" :precision="2" />
                <span class="unit">m³/s</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="危险流量">
                <el-input-number v-model="thresholdSettings.flow.danger" :precision="2" />
                <span class="unit">m³/s</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="极限流量">
                <el-input-number v-model="thresholdSettings.flow.critical" :precision="2" />
                <span class="unit">m³/s</span>
              </el-form-item>
            </el-col>
          </el-row>

          <h4>降雨阈值</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="小雨">
                <el-input-number v-model="thresholdSettings.rainfall.light" :precision="1" />
                <span class="unit">mm/h</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="中雨">
                <el-input-number v-model="thresholdSettings.rainfall.moderate" :precision="1" />
                <span class="unit">mm/h</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="大雨">
                <el-input-number v-model="thresholdSettings.rainfall.heavy" :precision="1" />
                <span class="unit">mm/h</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="暴雨">
                <el-input-number v-model="thresholdSettings.rainfall.storm" :precision="1" />
                <span class="unit">mm/h</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <!-- 用户管理 -->
      <el-tab-pane label="用户管理" name="user">
        <div class="user-management">
          <div class="user-actions">
            <el-button type="primary" @click="showAddUserDialog">
              <el-icon><Plus /></el-icon>
              添加用户
            </el-button>
            <el-button @click="showAddGroupDialog">
              <el-icon><UserFilled /></el-icon>
              添加用户组
            </el-button>
          </div>

          <el-tabs v-model="userTab" type="card">
            <el-tab-pane label="用户列表" name="users">
              <el-table :data="userList" stripe border>
                <el-table-column prop="name" label="姓名" />
                <el-table-column prop="phone" label="手机号" />
                <el-table-column prop="email" label="邮箱" />
                <el-table-column prop="department" label="部门" />
                <el-table-column prop="role" label="角色">
                  <template #default="{ row }">
                    <el-tag :type="getRoleTagType(row.role)">{{ getRoleText(row.role) }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                  <template #default="{ row }">
                    <el-switch v-model="row.status" @change="updateUserStatus(row)" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" @click="editUser(row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteUser(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <el-tab-pane label="用户组" name="groups">
              <el-table :data="groupList" stripe border>
                <el-table-column prop="name" label="组名" />
                <el-table-column prop="description" label="描述" />
                <el-table-column prop="memberCount" label="成员数量" />
                <el-table-column prop="createTime" label="创建时间" />
                <el-table-column label="操作" width="180">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" @click="editGroup(row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteGroup(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-tab-pane>

      <!-- 备份恢复 -->
      <el-tab-pane label="备份恢复" name="backup">
        <el-form :model="backupSettings" label-width="120px">
          <el-form-item label="自动备份">
            <el-switch v-model="backupSettings.autoBackup" />
            <span class="setting-desc">启用自动备份功能</span>
          </el-form-item>
          
          <el-form-item label="备份频率" v-if="backupSettings.autoBackup">
            <el-select v-model="backupSettings.backupFrequency" style="width: 200px">
              <el-option label="每日" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="备份时间" v-if="backupSettings.autoBackup">
            <el-time-picker
              v-model="backupSettings.backupTime"
              format="HH:mm"
              placeholder="选择备份时间"
            />
          </el-form-item>
          
          <el-form-item label="备份保留">
            <el-input-number v-model="backupSettings.retentionCount" :min="1" :max="30" />
            <span class="setting-desc">保留备份文件数量</span>
          </el-form-item>
          
          <el-form-item label="备份路径">
            <el-input v-model="backupSettings.backupPath" placeholder="/data/backup" style="width: 400px" />
          </el-form-item>
          
          <el-form-item label="手动操作">
            <el-button type="primary" @click="createBackup" :loading="backupLoading">
              <el-icon><Download /></el-icon>
              立即备份
            </el-button>
            <el-button @click="showRestoreDialog">
              <el-icon><Upload /></el-icon>
              恢复数据
            </el-button>
          </el-form-item>
        </el-form>

        <el-divider>备份历史</el-divider>
        <el-table :data="backupHistory" stripe border>
          <el-table-column prop="filename" label="文件名" />
          <el-table-column prop="size" label="大小" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="type" label="类型">
            <template #default="{ row }">
              <el-tag :type="row.type === 'auto' ? 'success' : 'info'">
                {{ row.type === 'auto' ? '自动' : '手动' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="downloadBackup(row)">下载</el-button>
              <el-button type="danger" size="small" @click="deleteBackup(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveSettings" :loading="saveLoading">
          <el-icon><Check /></el-icon>
          保存设置
        </el-button>
        <el-button type="success" @click="testConnection">
          <el-icon><Connection /></el-icon>
          测试连接
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  UserFilled,
  Download,
  Upload,
  Check,
  Connection
} from '@element-plus/icons-vue'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
})

const emit = defineEmits<Emits>()

const activeTab = ref('notification')
const userTab = ref('users')
const saveLoading = ref(false)
const backupLoading = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 通知设置
const notificationSettings = reactive({
  smsEnabled: true,
  smsProvider: 'aliyun',
  smsSignature: '水库监测系统',
  emailEnabled: true,
  smtpServer: 'smtp.163.com',
  smtpPort: 465,
  senderEmail: 'system@reservoir.com',
  wechatEnabled: false,
  wechatCorpId: '',
  wechatSecret: ''
})

// 系统设置
const systemSettings = reactive({
  warningFrequencyLimit: 5,
  dataRetentionDays: 365,
  autoCleanup: true,
  cleanupTime: new Date(2000, 0, 1, 2, 0),
  logLevel: 'info',
  maxConcurrency: 10,
  timeoutSeconds: 30,
  retryCount: 3
})

// 阈值设置
const thresholdSettings = reactive({
  waterLevel: {
    normal: 180.0,
    warning: 185.0,
    danger: 188.0,
    critical: 190.0
  },
  flow: {
    normal: 100.0,
    warning: 500.0,
    danger: 800.0,
    critical: 1000.0
  },
  rainfall: {
    light: 2.5,
    moderate: 8.0,
    heavy: 16.0,
    storm: 30.0
  }
})

// 备份设置
const backupSettings = reactive({
  autoBackup: true,
  backupFrequency: 'daily',
  backupTime: new Date(2000, 0, 1, 2, 0),
  retentionCount: 7,
  backupPath: '/data/backup'
})

// 用户列表
const userList = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138001',
    email: 'zhangsan@example.com',
    department: '运行部',
    role: 'admin',
    status: true
  },
  {
    id: 2,
    name: '李四',
    phone: '13800138002',
    email: 'lisi@example.com',
    department: '技术部',
    role: 'operator',
    status: true
  },
  {
    id: 3,
    name: '王五',
    phone: '13800138003',
    email: 'wangwu@example.com',
    department: '安全部',
    role: 'viewer',
    status: false
  }
])

// 用户组列表
const groupList = ref([
  {
    id: 1,
    name: '管理员组',
    description: '系统管理员',
    memberCount: 2,
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    name: '操作员组',
    description: '日常操作人员',
    memberCount: 5,
    createTime: '2024-01-16 14:20:00'
  }
])

// 备份历史
const backupHistory = ref([
  {
    id: 1,
    filename: 'backup_20241215_020000.sql',
    size: '15.2MB',
    createTime: '2024-12-15 02:00:00',
    type: 'auto'
  },
  {
    id: 2,
    filename: 'backup_20241214_143000.sql',
    size: '14.8MB',
    createTime: '2024-12-14 14:30:00',
    type: 'manual'
  }
])

// 获取角色标签类型
const getRoleTagType = (role: string) => {
  const roleMap = {
    admin: 'danger',
    operator: 'warning',
    viewer: 'info'
  }
  return roleMap[role] || 'info'
}

// 获取角色文本
const getRoleText = (role: string) => {
  const roleMap = {
    admin: '管理员',
    operator: '操作员',
    viewer: '查看者'
  }
  return roleMap[role] || role
}

// 保存设置
const saveSettings = async () => {
  saveLoading.value = true
  
  try {
    // 模拟保存设置
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('设置保存成功')
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('设置保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 测试连接
const testConnection = async () => {
  try {
    // 模拟测试连接
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('连接测试成功')
  } catch (error) {
    ElMessage.error('连接测试失败')
  }
}

// 显示添加用户对话框
const showAddUserDialog = () => {
  ElMessage.info('添加用户功能开发中...')
}

// 显示添加用户组对话框
const showAddGroupDialog = () => {
  ElMessage.info('添加用户组功能开发中...')
}

// 编辑用户
const editUser = (user: any) => {
  ElMessage.info(`编辑用户: ${user.name}`)
}

// 删除用户
const deleteUser = (user: any) => {
  ElMessageBox.confirm(`确定要删除用户 ${user.name} 吗？`, '确认删除', {
    type: 'warning'
  }).then(() => {
    const index = userList.value.findIndex(item => item.id === user.id)
    if (index > -1) {
      userList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

// 更新用户状态
const updateUserStatus = (user: any) => {
  ElMessage.success(`用户 ${user.name} 状态已更新`)
}

// 编辑用户组
const editGroup = (group: any) => {
  ElMessage.info(`编辑用户组: ${group.name}`)
}

// 删除用户组
const deleteGroup = (group: any) => {
  ElMessageBox.confirm(`确定要删除用户组 ${group.name} 吗？`, '确认删除', {
    type: 'warning'
  }).then(() => {
    const index = groupList.value.findIndex(item => item.id === group.id)
    if (index > -1) {
      groupList.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

// 创建备份
const createBackup = async () => {
  backupLoading.value = true
  
  try {
    // 模拟创建备份
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    const now = new Date()
    const filename = `backup_${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}${now.getSeconds().toString().padStart(2, '0')}.sql`
    
    backupHistory.value.unshift({
      id: Date.now(),
      filename,
      size: '16.5MB',
      createTime: now.toLocaleString(),
      type: 'manual'
    })
    
    ElMessage.success('备份创建成功')
  } catch (error) {
    ElMessage.error('备份创建失败')
  } finally {
    backupLoading.value = false
  }
}

// 显示恢复对话框
const showRestoreDialog = () => {
  ElMessage.info('数据恢复功能开发中...')
}

// 下载备份
const downloadBackup = (backup: any) => {
  ElMessage.success(`正在下载备份文件: ${backup.filename}`)
}

// 删除备份
const deleteBackup = (backup: any) => {
  ElMessageBox.confirm(`确定要删除备份文件 ${backup.filename} 吗？`, '确认删除', {
    type: 'warning'
  }).then(() => {
    const index = backupHistory.value.findIndex(item => item.id === backup.id)
    if (index > -1) {
      backupHistory.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 初始化数据
onMounted(() => {
  // 加载设置数据
})
</script>

<style scoped>
.setting-desc {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}

.unit {
  margin-left: 10px;
  color: #666;
}

h4 {
  margin: 20px 0 15px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
  color: #333;
  font-size: 14px;
}

.user-management {
  min-height: 400px;
}

.user-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-tabs--border-card) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.el-tab-pane) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-input-number) {
  width: 150px;
}

:deep(.el-table) {
  margin-top: 10px;
}
</style>